from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
from django.contrib import auth
import requests
import json , re , os
from .models import *


from django.contrib.auth.models import Permission, User


def _exists_env(env_name):
    data = Abhost.objects.filter(env=env_name).values()
    if data==None or len(data)==0:
        return False
    return True


def _get_service_name(service_id):
    data = Service.objects.filter(id=service_id).values()
    if data == None or len(data) ==0:
        return None
    return data[0].get('name',None)


def _get_abhost(env_name):
    print(Abhost.objects.all().values())
    data = Abhost.objects.filter(env=env_name).values()
    print(env_name,data)
    if data == None or len(data) == 0:
        return None
    return data[0].get('host',None)


def _get_abdata(abhost,method,system=None,uid=None,upstream=None):
    url = os.path.join(abhost, method)
    params = []
    if system != None:
        params.append("system=%s"%system)
    if uid !=None:
        params.append("uid=%s"%uid)
    if upstream !=None:
        params.append("upstream=%s"%upstream)

    if len(params)!=None:
        url = url+'?'+'&'.join(params)
    print(url)
    res = requests.get(url)
    if res.status_code != 200:
        return "error"
    text = res.text
    datas = json.loads(text).get('data',[])
    return datas

def _get_services():
    datas = Service.objects.all()
    newdatas = []
    for data in datas:
        newdatas.append({'id':data.id,
                         'group':data.group.name,
                         'name':data.name,
                         'desc':data.desc,
                         'setting':"<a href='{name}'>设置</a>".format(name=data.id)})
    return newdatas

def _get_devices():
    datas = Device.objects.all().values()
    if len(datas)==0:return None
    return datas

def _get_service_id(request):
    url_path = request.path
    return url_path.split('/')[4]


def _get_env_name(request):
    url_path = request.path
    return url_path.split('/')[2]


def abview_perm(view):
    def decorator(request, *args, **kwargs):
        if not request.user.is_authenticated():
            if request.method=='GET':
                return HttpResponseRedirect('/account/login')
            elif request.method == 'POST':
                return HttpResponse(json.dumps({'code':10010,'msg':'未登陆'}))
        if not request.user.has_perm('abview.abview_admin'):
            if request.method=='GET':
                return render(request, 'templates/403.html')
            elif request.method == 'POST':
                return HttpResponse(json.dumps({'code':10011,'msg':'无权限'}))
        return view(request, *args, **kwargs)

    return decorator


@csrf_exempt
@abview_perm
def services_view(request):
    # if not request.user.is_authenticated():
    #     return HttpResponseRedirect('/account/login')
    # if not request.user.has_perm('abview.modify_service'):
    #     return  render(request, 'templates/403.html')

    env_name = _get_env_name(request)

    if request.method == 'GET':
        abhost = _get_abhost(env_name)
        if not abhost:
            return render(request , 'templates/404.html')
        return render(request,'abview/templates/services.html',{})
    elif request.method == 'POST':
        services = _get_services()
        print(services)
        return HttpResponse(json.dumps(services))




@csrf_exempt
@abview_perm
def route_view(request):

    url_path = request.path
    env_name = _get_env_name(request)
    service_id = _get_service_id(request)
    abhost = _get_abhost(env_name)
    service_name = _get_service_name(service_id)
    if request.method == 'GET':

        if abhost==None or len(abhost)==0:
            return render(request , 'templates/404.html')
        if service_name == None:
            return render(request,'templates/404.html')

        devices = _get_devices()
        return render(request,'abview/templates/routes.html',{'system':service_name,"env_name":env_name,'devices':devices})
    elif request.method=='POST':


        abdatas = _get_abdata(abhost,'ab/get_all',system=service_name)
        newdatas  = []
        for data in abdatas:
            key = data['key']
            value = data['value']
            newkey = re.sub("uid_%s_" % service_name, '', key)
            newdatas.append({'env_name':env_name,'system':service_name,'uid':newkey,'upstream':value})
        return HttpResponse(json.dumps(newdatas, ensure_ascii=False))

@csrf_exempt
@abview_perm
def route_set(request):
    if request.method == "POST":
        # print(request.POST)
        strJson = request.POST.get('strJson', [])
        if strJson == [] or strJson == "":
            return HttpResponse("无设置项")

        data = json.loads(strJson)
        env_name  = data.get('env_name',None)
        system = data.get('system', None)
        uid = data.get('uid', None)
        upstream = data.get('upstream', None)
        if env_name!=None and system != None and uid != None and upstream != None:
            abhost = _get_abhost(env_name)
            if not abhost:
                # return render(request, 'templates/404.html')
                return HttpResponse("设置失败;缺少abhost")
            abdatas = _get_abdata(abhost,'ab/set', system=system, uid=uid, upstream=upstream)

            return HttpResponse("设置成功")
        else:
            return HttpResponse("设置失败;system、uid、upstream必填参数")

@csrf_exempt
@abview_perm
def route_delete(request):
    if request.method=="POST":
        # print(request.POST)
        strJson = request.POST.get('strJson',[])
        if strJson==[] or strJson == "":
            return HttpResponse("无设置项")
        if isinstance(strJson , str):
            datas = json.loads(strJson)
        if isinstance(datas , dict):
            datas = [datas]
        for data in datas:
            if isinstance(data,str):data = json.loads(data)
            env_name = data.get('env_name', None)
            system = data.get('system',None)
            uid = data.get('uid',None)
            upstream = data.get('upstream',None)
            if system !=None and uid!=None and upstream!=None:
                abhost = _get_abhost(env_name)
                if not abhost:
                    # return render(request, 'templates/404.html')
                    return HttpResponse("删除失败;缺少abhost")
                abdatas = _get_abdata(abhost, 'ab/del', system=system, uid=uid, upstream=upstream)
        return HttpResponse("删除成功")